//
//  SearchPartsInventoryViewController.m
//  HondaPro_2
//
//  Created by Eric on 13-6-8.
//  Copyright (c) 2013年 glendale. All rights reserved.
//

#import "SearchPartsInventoryViewController.h"
#import "MainViewController.h"
#import "MainMenuDataModel.h"
#import "MyAFNetWorkManager.h"
#import "MJRefresh.h"
#import "DDPopoverBackgroundView.h"
#import "popContentViewController.h"

@interface SearchPartsInventoryViewController ()<ContentViewControllerDelegate>
{
    NSMutableArray *allArr;
    
    popContentViewController *contentCon;
    UIButton *selectBtn;
    NSMutableArray *lingjianArr;
}
@property(nonatomic,strong)UIPopoverController *popCon;
//创建子视图
-(void)createSubView;

@end

@implementation SearchPartsInventoryViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    from = 1;
    to = 10;
    
    [self createTitle];
    [self createSubView];
    
    //初始化所有的输入框
    partCodeTextField.text = @"";
    partChinaNameTextField.text = @"";
    partEnglishNameTextField.text = @"";
    carTypeIdTextField.text = @"";
    
    //初始化复选按钮的状态－－－选中
    [MainMenuDataModel sharedMainMenuDataModel].strInStock = @"1";
    lingjianArr = [NSMutableArray arrayWithCapacity:5];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
//    [self addAllObserver];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [allArr removeAllObjects];
//    [self removeAllObserver];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 创建子视图

-(void)createSubView
{
    UILabel *bgLbl = [[UILabel alloc] initWithFrame:CGRectMake(43, 280, 940, 250)];
    bgLbl.backgroundColor = [UIColor clearColor];
    
    sv = [[subViewForSearchPartsInventoryView alloc] initWithFrame:CGRectMake(43+1, 280+1, 940-2, 250-2+200)];
    sv.backgroundColor = [UIColor clearColor];
    
    [self.view addSubview:bgLbl];
    [self.view addSubview:sv];
    
    allArr = [NSMutableArray arrayWithCapacity:5];
    __unsafe_unretained UITableView *table = sv.tableViewDis;
    table.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        [allArr removeAllObjects];
        to = 10;
        [self searchBtnPressed:nil];
        [table.mj_header endRefreshing];
    }];
    
    
    table.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        to = to+10;
        [self searchBtnPressed:nil];
        [table.mj_footer endRefreshing];
    }];
}

#pragma mark - 回调方法

- (IBAction)backBtnPressed:(UIButton *)sender
{
//    NSLog(@"backBtnPressed !!!");
    
    //返回上一级界面
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)inStockBtnPressed:(UIButton *)sender
{
//    NSLog(@"inStockBtnPressed !!!");
    
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    if ([modelIns.strInStock isEqualToString:@"0"])
    {
        //给button上放置一个方框
        UIButton *btn = sender;
        [btn setBackgroundImage:[UIImage imageNamed:@"对号.png"] forState:UIControlStateNormal];
        [MainMenuDataModel sharedMainMenuDataModel].strInStock = @"1";
    }
    else
    {
        //给button上放置一个箭头
        UIButton *btn = sender;
        [btn setBackgroundImage:[UIImage imageNamed:@"对号框.png"] forState:UIControlStateNormal];
        [MainMenuDataModel sharedMainMenuDataModel].strInStock = @"0";
    }
}

- (IBAction)searchBtnPressed:(UIButton *)sender
{
//    NSLog(@"searchBtnPressed !!!");
    
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    //(1)更新信息类中要上传的数据
    modelIns.strPartCodeForSearchPartsInventory = partCodeTextField.text;
    modelIns.strPartChinaNameForSearchPartsInventory = partChinaNameTextField.text;
    modelIns.strPartEnglishNameForSearchPartsInventory = partEnglishNameTextField.text;
    modelIns.strCarTypeId = carTypeIdTextField.text;
    modelIns.arrForSearchPartsInventory = nil;
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:4];
    
    //(2)调用接口，并给模型类的数组赋值
    /*
     just for test
     */
//    [modelIns jsonParseFromSearchPartsInventory];
//    webService *mmWebSearchInventory = [[webService alloc] init];
//    mmWebSearchInventory.methodName = MM_SEARCH_PARTS_INVENTORY_;
    arrTmp = [[NSMutableArray alloc] init];
//    _from = 0-10;
//    _to = 0;
    
    
    [dic setValue:modelIns.strInStock forKey:@"IN_STOCK"];
    
    if (![modelIns.strPartCodeForSearchPartsInventory isEqualToString:@""])
    {
        [dic setValue:[modelIns.strPartCodeForSearchPartsInventory stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] forKey:@"PART_CODE"];
    }
    
    if (![modelIns.strPartChinaNameForSearchPartsInventory isEqualToString:@""])
    {
        [dic setValue:[modelIns.strPartChinaNameForSearchPartsInventory stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] forKey:@"PART_CHINA_NAME"];
    }
    
    if (![modelIns.strPartEnglishNameForSearchPartsInventory isEqualToString:@""])
    {
        
        [dic setValue:[modelIns.strPartEnglishNameForSearchPartsInventory stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] forKey:@"PART_ENGLISH_NAME"];
     
    }
    
    
//    [dic setValue:[NSString stringWithFormat:@"%d",allArr.count+1] forKey:@"FROM"];
//    [dic setValue:[NSString stringWithFormat:@"%d",allArr.count+10] forKey:@"TO"];
    if (selectBtn.titleLabel.text.length != 0 && ![selectBtn.titleLabel.text isEqualToString:@"< 空 >"]) {
          [dic setValue:self.lingjianleibieID forKey:@"CAR_CLASS"];
    }
    NSString * fromStr = [NSString stringWithFormat:@"%d",from];
     NSString * toStr = [NSString stringWithFormat:@"%d",to];
    [dic setValue:fromStr forKey:@"FROM"];
      [dic setValue:toStr forKey:@"TO"];
    //请求新的数据
    //[self updateTheAsyPartsData];
    [SVProgressHUD showWithStatus:@"请等待..."];
    NSLog(@"零件查询-----------%@",dic);
    [MyAFNetWorkManager postWithParam:dic andAction:@"QUERY_PART_STOCK_PAD" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
        NSLog(@"---%@",obj);
        [SVProgressHUD dismiss];
        if (!error) {
            NSArray *array = [obj objectForKey:@"TM_PART_INFO"];
            [allArr removeAllObjects];
            [allArr addObjectsFromArray:array];
            MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
            modelIns.arrForSearchPartsInventory = allArr;
            [sv setNeedsDisplay];
        }
        else{
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        }
        
    }];
}

//回调方法
-(void)huidiao:(NSNotification *)notification
{
    NSDictionary *theJson = [NSJSONSerialization JSONObjectWithData:(NSData*)notification.object options:NSJSONReadingMutableLeaves error:Nil];
    
//    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
//    modelIns.arrForSearchPartsInventory = [theJson objectForKey:@"results"];
    
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    NSArray *arrForTmp = [theJson objectForKey:@"results"];
    
    //将arrForTmp里边的数据添加进数据模型中
    if (nil != modelIns.arrForSearchPartsInventory)
    {
        NSMutableArray *arrMutableTmp = [NSMutableArray arrayWithArray:modelIns.arrForSearchPartsInventory];
        for (int i = 0; i<[arrForTmp count]; i++)
        {
            [arrMutableTmp addObject:[arrForTmp objectAtIndex:i]];
        }
        modelIns.arrForSearchPartsInventory = arrMutableTmp;
    }
    else
    {
        modelIns.arrForSearchPartsInventory = arrForTmp;
    }
    
    //dismiss 掉菊花效果
    [SVProgressHUD dismiss];
    
    //刷新界面数据
    [sv setNeedsDisplay];
}

#pragma mark - 创建标题

-(void)createTitle
{
    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(150, 20, 180, 50)];
    lbl.textColor = [HelpClass colorWithHexString:@"666666"];
    lbl.font = [UIFont systemFontOfSize:30];
    lbl.text = @"零件查询";
    [self.view addSubview:lbl];
    
    
    [self setupDropdownLabelWithFrame:CGRectMake(596, 114, 319, 30)];
    selectBtn = [self setupDropdownButtonWithFrame:CGRectMake(597, 115, 317, 28) action:@selector(selectLingJian:)];
    
}

-(void)setupDropdownLabelWithFrame:(CGRect)frame{
    UILabel *label1 = [[UILabel alloc]initWithFrame:frame];
    [label1 setBackgroundColor:[UIColor clearColor]];
    label1.layer.borderColor = [[UIColor blackColor]CGColor];
    label1.layer.borderWidth = 1;
    [self.view addSubview:label1];
}

-(UIButton *)setupDropdownButtonWithFrame:(CGRect)frame action:(SEL)method
{
    UIButton *btn = [[UIButton alloc]initWithFrame:frame];
    [btn setBackgroundImage:[UIImage imageNamed:@"下拉框.png"] forState:UIControlStateNormal];
    [btn addTarget:self action:method forControlEvents:UIControlEventTouchUpInside];
    [btn setTitle:@"< 空 >" forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont fontWithName:@"ArialMT" size:16];
    [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.view addSubview:btn];
    return btn;
}


//注册消息
-(void)addAllObserver
{
    //注册消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(huidiao:) name:MM_SEARCH_PARTS_INVENTORY_ object:nil];
    
    //注册一个消息，@“searchPartInventoryToUpdateTheAsyPartsData”,用来刷新数据
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateTheAsyPartsData) name:@"searchPartInventoryToUpdateTheAsyPartsData" object:nil];
}

//刷新数据的方法
-(void)updateTheAsyPartsData
{
//    webService *mmWebSearchInventory = [[webService alloc] init];
//    mmWebSearchInventory.methodName = MM_SEARCH_PARTS_INVENTORY_;
//    _from = _to;
//    _to += 10;
//    [arrTmp setObject:[NSString stringWithFormat:@"%i",_from] atIndexedSubscript:[arrTmp count]-1-2];
//    [arrTmp setObject:[NSString stringWithFormat:@"%i",_to] atIndexedSubscript:[arrTmp count]-1-0];
//    [mmWebSearchInventory commonGetSharedRequest:mmWebSearchInventory.methodName wsparas:arrTmp];
    
    //菊花效果
    [SVProgressHUD show];
    
    //刷新界面数据
    [sv setNeedsDisplay];
}

//移除消息
-(void)removeAllObserver
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//将home键的图标变成返回键的图标
-(void)replaceHomeBtnByBAckBtn
{
    [((UIButton *)[self.view viewWithTag:100]) setImage:[UIImage imageNamed:@"返回.png"] forState:UIControlStateNormal];
}

- (void)selectLingJian:(UIButton *)sender
{
    if (!contentCon) {
        contentCon=[[popContentViewController alloc] initWithNibName:@"popContentViewController" bundle:nil];
    }
    contentCon.delegate = self;
    contentCon.btnSender=sender;
    self.popCon = [[UIPopoverController alloc] initWithContentViewController:contentCon];
    [DDPopoverBackgroundView setTintColor:[UIColor colorWithRed:234 green:248 blue:242 alpha:0.9]];
    [DDPopoverBackgroundView setArrowBase:30.0];//箭头
    [DDPopoverBackgroundView setArrowHeight:15.0];
    [DDPopoverBackgroundView setContentInset:1.0];
    [self.popCon setPopoverBackgroundViewClass:[DDPopoverBackgroundView class]];
    [self.popCon setPopoverContentSize:CGSizeMake(selectBtn.frame.size.width, 160)];
    [self.popCon presentPopoverFromRect:CGRectMake(95, 0, 135, 20) inView:sender permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
    
    NSArray *zidianArr=[self readershuDICimform][@"TM_PART_TYPE"];
    NSMutableArray *modelArr = [[NSMutableArray alloc]init];
    [lingjianArr removeAllObjects];
    
    for(NSDictionary *dic in zidianArr)
    {
        [modelArr addObject:dic[@"NAME"]];
        [lingjianArr addObject:dic[@"CODE"]];
    }
    [modelArr insertObject:@"< 空 >" atIndex:0];
    contentCon.list = modelArr;
    
    [contentCon.myTableView reloadData];
}

-(void) selectDelegate:(NSInteger) row btn:(UIButton*)btn
{
    if (btn == selectBtn) {
        if (row==0) {
            [selectBtn setTitle:@"< 空 >" forState:UIControlStateNormal];
        }
        else{
            self.lingjianleibieID = [lingjianArr objectAtIndex:row];
        }
    }
    
    NSLog(@"%@---",self.lingjianleibieID);
    [self.popCon dismissPopoverAnimated:YES];
    self.popCon = nil;
}

-(NSMutableDictionary *)readershuDICimform
{
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path=[paths objectAtIndex:0];
    NSString *str=[path stringByAppendingPathComponent:@"Dic.text"];
    dic=[NSMutableDictionary dictionaryWithContentsOfFile:str];
    //nslog(@"%@",dic);
    return dic;
}

@end
